package com.cande.jni.bytetest;


import org.agrona.concurrent.UnsafeBuffer;
import sun.nio.ch.DirectBuffer;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;

public class ByteTest {
    static {
        System.loadLibrary("mycppcode"); // 加载C++库
    }

    // 声明本地方法
    public native void readPersonData(byte[] data);

    public native byte[] returnPersonData();
    public native byte[] testDirectMem(long addr);


    public static void main(String[] args) {
        // 创建一个ByteBuffer，按小端字节序写入数据
        ByteBuffer buffer = ByteBuffer.allocateDirect(4+50 + 8 + 4 + 4); // name + id + age + height
        buffer.order(ByteOrder.LITTLE_ENDIAN);



        long address = ((DirectBuffer)buffer).address();



        // 写入数据
        String name = "Alice";
        byte[] nameBytes = name.getBytes();
        buffer.putInt(1);
        buffer.put(nameBytes);
        buffer.position(54); // 确保name字段为50字节
        buffer.putLong(1234567890123456789L); // 写入long类型id
        buffer.putInt(30); // 写入int类型age
        buffer.putFloat(1.65f); // 写入float类型height

        // 获取字节数组
//        byte[] data = buffer.array();

        // ByteTest
        ByteTest myClass = new ByteTest();
//        myClass.readPersonData(data);

        myClass.testDirectMem(address);


        UnsafeBuffer unsafeBuffer = new UnsafeBuffer(address, 4+50 + 8 + 4 + 4);

        System.out.println("unsafeBuffer.getInt(0) = " + unsafeBuffer.getInt(0));
        byte[] nameByte = new byte[50];
        unsafeBuffer.getBytes(4,nameByte,0,50);
        System.out.println("unsafeBuffer.getStringUtf8(4) = " + new String(nameBytes,StandardCharsets.UTF_8));

        byte[] result = myClass.returnPersonData();

        ByteBuffer resultBuffer = ByteBuffer.wrap(result);

        // 设置大端字节序
        resultBuffer.order(ByteOrder.LITTLE_ENDIAN);

        byte[] strRes = new byte[50];
        resultBuffer.get(strRes, 0 ,50);

        System.out.println(new String(strRes, StandardCharsets.UTF_8));

        System.out.println("resultBuffer.getLong(50) = " + resultBuffer.getLong(50));
        System.out.println("resultBuffer.getLong(58) = " + resultBuffer.getInt(58));
    }
}
